package com.dong.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dong.common.util.UserUtils;
import com.dong.module.user.pojo.User;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 自动填充配置
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        Date now = new Date();
        User user = null;
        user = UserUtils.getUser();
        String name = "System";
        if (StringUtils.isNotBlank(user.getId())) {
            name = user.getId();
        }
        String finalName = name;
        this.strictInsertFill(metaObject, "createTime", () -> now, Date.class);
        this.strictInsertFill(metaObject, "createUser", () -> finalName, String.class);
        this.strictInsertFill(metaObject, "updateTime", () -> now, Date.class);
        this.strictInsertFill(metaObject, "updateUser", () -> finalName, String.class);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        Date now = new Date();
        User user = null;
        user = UserUtils.getUser();
        String name = "System";
        if (StringUtils.isNotBlank(user.getId())) {
            name = user.getId();
        }
        String finalName = name;
        this.strictUpdateFill(metaObject, "updateTime", () -> now, Date.class);
        this.strictUpdateFill(metaObject, "updateUser", () -> finalName, String.class);
    }



}